/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName CustomLoader.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.loader
{
	
	import com.gesturesoft.imultimax.AppConst;
	import com.gesturesoft.imultimax.events.CustomProgressEvent;
	import com.gesturesoft.imultimax.model.loader.events.LoadFaultEvent;
	import com.gesturesoft.imultimax.model.loader.events.LoadResultEvent;
	import com.gesturesoft.imultimax.model.loader.interfaces.ILoader;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class CustomLoader extends EventDispatcher implements ILoader
	{
		
		private var _url:String;
		private var netConnected:Boolean = true;
		
		public function CustomLoader(url:String)
		{
			
			this._url = url;
			
		}
		
		public function load():void
		{
			
			var urlloader:URLLoader = new URLLoader();
			urlloader.addEventListener(Event.COMPLETE, onComplete);
			urlloader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			urlloader.addEventListener(IOErrorEvent.IO_ERROR, onLoadFailed);
			urlloader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			urlloader.load(new URLRequest(_url));
			
		}
		
		private function onProgress(e:ProgressEvent):void{
			dispatchEvent(new CustomProgressEvent(CustomProgressEvent.LOAD_PROGRESS,e.bytesLoaded,e.bytesTotal));
		}
			
		private function onComplete(event : Event):void
		{
			
			URLLoader(event.target).removeEventListener(Event.COMPLETE, onComplete);
			dispatchEvent( new LoadResultEvent( LoadResultEvent.LOAD_COMPLETE, event.target.data ) );
			
		}
		
		private function onLoadFailed(event : IOErrorEvent):void
		{
			
			if(netConnected)
			{
				
				URLLoader(event.target).removeEventListener(IOErrorEvent.IO_ERROR, onLoadFailed);
				dispatchEvent( new LoadFaultEvent( LoadFaultEvent.LOAD_FAILED, AppConst.READ_ERROR ) );
				
			}
			
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void
		{
			
			if(event.status == 0)
			{
				
				netConnected = false;
				dispatchEvent(new LoadFaultEvent(LoadFaultEvent.LOAD_FAILED, AppConst.NET_CONNECTION_FAILED));
				
			}
			
		}
		
	}
	
}